import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store'
import { Toast, Dialog } from 'vant'

const routes = [
  {
    path: '/',
    name: 'dashboard',
    redirect: '/home',
    meta: {
      name: '首页'
    }
  },
  // 错误路由跳转
  {
    path: '/:pathMatch(.*)',
    redirect: "/404",
    meta: {
      name: 'notFound'
    }
  },
  {
    path: '/home',
    name: 'home',
    meta: {
      name: '首页'
    },
    component: ()=>import('@/views/home.vue')
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      name: '登录'
    },
    component: ()=>import('@/views/login.vue')
  },
  {
    path: '/401',
    name: '401',
    meta: {
      name: 'notAuth'
    },
    component: () => import('@/views/error/401.vue')
  },
  {
      path: '/404',
      name: '404',
      meta: {
        name: 'notFound'
      },
      component: () => import('@/views/error/404.vue')
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 登录之前做一个判断 ,判断它进入其它页面有没有先登录,
router.beforeEach((to, from, next) => {
  // 判断有没有登录
  const isLogin = store.state.user.username ? true : false
  // const isLogin = true
  // 如果当前访问的是登录页面或者注册页面可以让它进入
  if (to.path == '/login' || to.path == "/register") {
      next()
  } else {
      // 如果isLogin为true表示已经登录了;就让它正常进入就可以 ,如果没登录就让他进入登录页面
      isLogin ? next() : next('/login')
  }

   // 设置标题
   document.title = to.meta.name || 'hyduan'
   // 路由跳转后，页面回到顶部
   document.body.scrollTop = 0
   document.documentElement.scrollTop = 0
   window.scrollTo(0, 0)
  //  清空弹框等
   Toast.clear()
   Dialog.close()

})

router.onError(error => {
  console.log(error, '1212')
});

export default router
